package com.example.soss.interceptor;

import com.alibaba.fastjson.JSON;
import com.example.soss.annotation.AccessLimit;
import com.example.soss.entity.Result;
import com.example.soss.entity.ResultEnum;
import com.example.soss.util.AccessLimitUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;


/**
 * 访问限流拦截器
 */
@Component
@Slf4j
public class AccessLimitInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            //拿到方法上面的注解
            AccessLimit accessLimit = handlerMethod.getMethodAnnotation(AccessLimit.class);
            if (accessLimit != null) {

                String value = accessLimit.value();
                if (value.equals("page")) {
                    if (!AccessLimitUtil.pageTryAcquire(1500, TimeUnit.MILLISECONDS)) {
                        //返回当前访问人数过多提示
                        response(request, response);
                        return false;
                    }
                } else {
                    if (!AccessLimitUtil.selectTryAcquire(1500, TimeUnit.MILLISECONDS)) {
                        //返回当前访问人数过多提示
                        response(request, response);
                        return false;
                    }
                }
            }
        }
        return true;
    }


    public void response(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String xRequestedWith = request.getHeader("x-requested-with");
        if ("XMLHttpRequest".equals(xRequestedWith)) {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(Result.failure(ResultEnum.WAIT)));
            writer.close();
        } else {
            response.sendRedirect(request.getContextPath() + "/401");
        }
        log.info("接口限流拦截。。。");
    }


}
